const createModel = require('../mongodb/createModel')
const { handleDel } = require('./student')

const schema = {
  username: String,
  password: String,
  phoneNum: String,
  address: String,
  createTime: {
    type: Date,
    default: Date.now
  }
}

const userModel = createModel('users', schema)

//查询用户列表
const findUserList = () => {
  return new Promise((resolve, reject) => {
    // userModel.find({}, (err, docs) => {
    //   console.log('---err---', err, '---docs---', docs)
    //   if(docs){
    //     resolve({
    //       status: 1,
    //       data: docs
    //     })
    //   }else{
    //     reject({
    //       status: 0
    //     })
    //   }
    // })

    //按照时间排序 sort('-createTime') ，前面加 负号 表示从大到小排序，不加则从小到大排序
    userModel.find().sort('-createTime').exec((err, docs) => {
      if(docs){
        resolve({
          status: 1,
          data: docs
        })
      }else{
        reject({
          status: 0
        })
      }
    })
  })
}


//删除用户 deleteOne
const handleDeleteUser = (id) => {
  return new Promise((resolve, reject) => {
    userModel.deleteOne({_id: id}, (err) => {
      console.log('---id---', id, '---err---', err)
      if(!err){
        resolve({
          status: 1,
          message: '删除成功'
        })
      }else{
        reject({
          status: 0,
          message: '删除失败'
        })
        throw err
      }
    })
  })
}

//添加用户 create
const handleAddUser = (params) => {
    return new Promise((resolve, reject) => {
      if(params && params.username && params.password && params.phoneNum){
        userModel.create(params, (err, docs) => {
            console.log('---err---', err, '---docs---', docs)
            if(docs){
              resolve({
                status: 1,
                message: '添加成功'
              })
            }else{
              reject({
                status: 0,
                message: '添加失败'
              })
              throw err
            }
        })
      }else{
        reject({
            status: 0,
            message: '用户名，密码和手机号码是必填项'
        })
      }
      
    })
}

//修改用户 根据id查找某条数据，然后修改，findByIdAndUpdate(id,要修改的参数对象，回调函数docs是修改前的值)
const handleUpdateUser = (params) => {
  return new Promise((resolve, reject) => {
    userModel.findByIdAndUpdate(params.id, params, (err, docs) => {
      console.log('---params---', params, '---err---', err, '---docs---', docs)
      if(docs){
        resolve({
          status: 1,
          message: '修改成功'
        })
      }else{
        reject({
          status: 0,
          message: '修改失败'
        })
      }
    })
  })
}

module.exports = {
  findUserList,
  handleDeleteUser,
  handleAddUser,
  handleUpdateUser
}